﻿using Api.Shared.Model.Web.Login;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class LoginController : ControllerBase
    {
        private readonly MySession mySession;
        private readonly ILogger<LoginController> logger;
        private readonly ISugarClientService helper;

        public LoginController(
            MySession mySession,
            ILogger<LoginController> logger,
            [FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper
        )
        {
            this.mySession = mySession;
            this.logger = logger;
            this.helper = helper;
        }

        [HttpPost]
        public async Task<ActionResult<ApiResponse>> Login(LoginForm loginForm)
        {
            string? userName = loginForm.UserName;
            string? password = loginForm.Password;
            //var user = factoryService.UserService.FindUserByNameAndPwd(userName, password);

            try
            {
                var user = await this.helper.Db.Queryable<User>().Where(x => x.UserName == userName && x.Password == password).FirstAsync();
                if (user == null)
                {
                    return StatusCode(204, "无此用户");
                }
                mySession.MyToken = userName;
                mySession.user = user;

                LoginForm loginForm2 =
                    new()
                    {
                        Password = password,
                        UserName = userName,
                        Token = userName
                    };

                logger.LogInformation($"用户 {userName} 已经登陆");

                return Ok(
                    new ApiResponse<LoginForm>()
                    {
                        Code = 200,
                        Count = 1,
                        Data = loginForm2,
                        Message = "Success！"
                    }
                );
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return BadRequest(ex.Message);

            }

        }
    }
}
